package fm.yichenet.mongo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import fm.dao.MongoBaseDao;
import fm.dto.NeiyiUser;
import fm.dto.UserAddress;
import fm.dto.NeiyiUser;
import fm.exception.BizException;
import fm.mongo.MCondition;
import fm.mongo.MRel;
import fm.mongo.MongoTable;
import fm.mongoService.UserService;
import fm.web.CurrentRequest;
import fm.yichenet.mongo.service.MerchantUserService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by CM on 2017/6/17.
 */
@Service
public class MerchantUserServiceImpl implements MerchantUserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(MerchantUserService.class);

    @Autowired
    UserService userService;
    @Autowired
    MongoBaseDao mongoBaseDao;

    @Override
    public void updateMerchantAuthInfo(Map param) throws Exception {
        String address = (String) param.get("address");
        String province = (String) param.get("province");
        String city = (String) param.get("city");
        String district = (String) param.get("district");
        String street = (String) param.get("street");
        String streetNumber = (String) param.get("street_number");

        String loc = (String) param.get("loc");
        String userId = (String) CurrentRequest.getCurrentUserId();

        if (userId == null) {
            throw new BizException("用户不存在！");
        }

        if (StringUtils.isEmpty(loc)) {
            throw new BizException("未获取到详细的经纬度坐标，更新地址信息失败!");
        }

        NeiyiUser user = userService.getById(userId);


        if (user == null) {
            throw new BizException("未找到用户信息，更新地址信息失败!");
        }


        UserAddress userAddress = user.getUserAdd();
        userAddress.setProvince(province);
        userAddress.setCity(city);
        userAddress.setDetailAddress(street);

        double lat = Math.min(Double.parseDouble(loc.split(",")[0]), Double.parseDouble(loc.split(",")[1]));
        double lng = Math.max(Double.parseDouble(loc.split(",")[0]), Double.parseDouble(loc.split(",")[1]));

        user.setLat(new BigDecimal(lat));
        user.setLng(new BigDecimal(lng));

        DBObject updateObject = new BasicDBObject();

        if (StringUtils.isNotEmpty(province)) {
            updateObject.put("province", province);
        }

        if (StringUtils.isNotEmpty(city)) {
            updateObject.put("city", city);
        }
        if (StringUtils.isNotEmpty(district)) {
            updateObject.put("district", district);
        }
        if (StringUtils.isNotEmpty(street)) {
            updateObject.put("street", street);
        }

        if (StringUtils.isNotEmpty(streetNumber)) {
            updateObject.put("streetNumber", streetNumber);
        }
        if (StringUtils.isNotEmpty(loc)) {
            updateObject.put("loc", loc);
        }
        if (StringUtils.isNotEmpty(address)) {
            updateObject.put("address", address);
        }

        DBObject queryObject = new BasicDBObject("id", userId);
        mongoBaseDao.updateOne(queryObject.toMap(), updateObject.toMap(), MongoTable.merchant_auth_info);
        Map params= new HashMap<>();
        params.putAll(JSON.parseObject(JSON.toJSONString(user)));
        userService.updateUserInfo(new BasicDBObject("id",userId).toMap(),params);
        LOGGER.info("update user address information success:{}", JSON.toJSONString(param));
    }

    @Override
    public DBObject getAuthInfoByUserIdAndType(Long userId, Integer userType) throws Exception {
        MCondition mc = MCondition.create(MRel.and);
        DBObject authInfo = null;
        switch (userType) {
            case 3:
            case 4:
                mc.append("id", userId);
                authInfo = (DBObject) mongoBaseDao.findOne(mc.toDBObject().toMap(), DBObject.class, MongoTable.merchant_auth_info);
                break;
            case 2:
                mc.append("user_id", userId);
                authInfo = (DBObject) mongoBaseDao.findOne(mc.toDBObject().toMap(), DBObject.class, MongoTable.engineer_auth_info);
                break;
            case 0:
                authInfo = new BasicDBObject();
                break;
            default:
                throw new BizException("错误的用户类型！");
        }

        return authInfo;
    }
}
